#coding:utf-8
from urllib import urlopen
from lovewith.api.weibo.weibo import APIClient
from lovewith.settings import SITE_URL


class Weibo:
    def __init__(self, token=None):
        # app key
        app_key = '87546181'
        # app secret
        app_secret = '4ce900393623a2db3e3e51102f9e0679'
        # callback url
        redirect_uri = '%su/auth/sina/' % SITE_URL

        if token:
            self.token = token

        self.client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=redirect_uri)

    #获取用户联系邮箱
    def get_user_email(self):
        try:
            email_item = self.client.account.profile.email.get()
            if email_item:
                return email_item.get('email')
        except StandardError, api_error:
            return None

    #获取登录url
    def get_login_server(self):
        return self.client.get_authorize_url()

    #关注某人
    def follow(self, userid):
        try:
            result = self.client.friendships.create.post(access_token=self.token, uid=userid)
        except StandardError, api_error:
            pass

    #获取授权token
    def get_token(self, code):
        return self.client.request_access_token(code)

    #保存token
    def save_token(self, token, expires):
        self.token = token
        self.client.set_access_token(token, expires)

    #获取授权用户uid
    def get_token_uid(self):
        return self.client.get.account__get_uid().uid

    #发布一条文字微博
    def post_text(self, content):
        #content = urlquote(content)
        try:
            self.client.statuses.update.post(access_token=self.token, status=content)
        except StandardError, api_error:
            pass

    #发送一条图片微博
    def post_with_pic(self, content, pic):
        if pic.find('http') < 0:
            pic_handle = open(pic, 'rb')
        else:
            pic_handle = urlopen(pic)

        try:
            self.client.statuses.upload.post(access_token=self.token, status=content, pic=pic_handle)
        except StandardError, api_error:
            pass

    #查找用户
    def find_user(self, q):
        result = self.client.search.suggestions.at_users.get(access_token=self.token, q=q, count=20, type=0)
        return result

    #获取用户详细信息
    def get_user_unfo(self, uid):
        user_data = self.client.users.show.get(access_token=self.token, uid=uid)
        return user_data